var express = require('express');
var router = express.Router();
const path = require('path');
const fs = require('fs');
// sql
const query = require('../mysql');
// 上传模块
const multer = require('multer');
const upload = multer({
	dest: path.join(__dirname, '../../public/file/patent'),
});

let patentAddForm;
// 获取
router.get('/', async (req, res) => {
	let { pagenum, pagesize } = req.query.queryInfo;
	let { username } = req.query;
	let inputQuery = req.query.queryInfo.query;
	let result;
	// console.log('inputQuery', inputQuery);
	if (inputQuery == '') {
		let sqlStr = `select * from patent  where inventor like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${username}%`]);
	} else {
		let sqlStr = `select * from patent where name like ? and inventor like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${inputQuery}%`, `%${username}%`]);
	}
	res.send({ status: 200, result });

	// 查询总数量
	let sqlStr1 = `select count(*) from patent`;
	let result1 = await query(sqlStr1);

	// 搜索功能
	res.send({ status: 200, result, total: result1[0]['count(*)'] });
});

// 上传
router.post('/', async (req, res, next) => {
	patentAddForm = req.body.patentAddForm;
	let sqlStr = `select * from patent where authorized_patent_no=?`;
	let result = await query(sqlStr, [patentAddForm.authorized_patent_no]);
	if (result.length != 0) {
		return res.send({ status: 401, message: '授权专利号重复' });
	}
	res.send({ status: 200, message: '创建信息成功' });
});

router.post('/upload', upload.single('file'), async (req, res, next) => {
	file = req.file;
	savePatent(file, req, res);
});

async function savePatent(file, req, res) {
	let {
		name,
		inventor,
		inventor_type,
		unit,
		patent_type,
		patent_scope,
		authorized_patent_no,
		authorization_time,
		apply_no,
		apply_time,
		subject_classification,
		status,
		remarks,
	} = patentAddForm;
	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/patent/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `insert into patent(name,inventor,inventor_type,unit,patent_type,patent_scope,authorized_patent_no,authorization_time,apply_no,apply_time,subject_classification,status,patentfile,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`;

	let result = await query(sqlStr, [
		name,
		inventor,
		inventor_type,
		unit,
		patent_type,
		patent_scope,
		authorized_patent_no,
		authorization_time,
		apply_no,
		apply_time,
		subject_classification,
		status,
		`/file/work/${name}.${extName}`,
		remarks,
	]);
	res.send({ status: 200, message: 'upload award success' });
}

// 修改获奖
let patentEditForm;
router.post('/edit', async (req, res) => {
	patentEditForm = req.body.patentEditForm;
	res.send({ status: 100, message: '创建获奖信息成功' });
});

// 修改获奖
router.post('/edit/upload', upload.single('file'), async (req, res) => {
	file = req.file;
	saveEditFile(file, req, res);
});

async function saveEditFile(file, req, res) {
	let {
		name,
		inventor,
		inventor_type,
		unit,
		patent_type,
		patent_scope,
		authorized_patent_no,
		authorization_time,
		apply_no,
		apply_time,
		subject_classification,
		status,
		remarks,
		patentfile,
	} = patentEditForm;
	console.log(patentEditForm);
	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/patent/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);
	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});
	let prevFile = path.join(__dirname, `../../public${patentfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `update patent set name = ?,inventor=?,inventor_type = ?,unit = ?,patent_type = ?,patent_scope = ?,authorized_patent_no = ?,authorization_time = ?,apply_no = ?,apply_time = ?,subject_classification = ?,status = ?,remarks  = ? ,patentfile = ? where id = ?`;
	let result = await query(sqlStr, [
		name,
		inventor,
		inventor_type,
		unit,
		patent_type,
		patent_scope,
		authorized_patent_no,
		authorization_time,
		apply_no,
		apply_time,
		subject_classification,
		status,
		remarks,
		`file/patent/${name}.${extName}`,
		patentEditForm.id,
	]);
	res.send({ status: 200, message: 'success' });
}

// 删除著作
router.delete('/', async (req, res) => {
	let reqQuery = req.query;
	// console.log(query);

	let prevFile = path.join(__dirname, `../../public${reqQuery.awardfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `delete from patent where id = ?`;
	let result = query(sqlStr, [reqQuery.id]);
	if (!result) {
		res.send({ status: 404, message: 'delete faile' });
	}
	res.send({ status: 200, message: 'delete suceess' });
});

module.exports = router;
